<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>并发——深入分析CountDownLatch的实现原理 | 博客主页 | 世界是个球，前方总有路！</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="并发">
    <meta name="description" content="一、前言&amp;emsp;&amp;emsp;最近在研究java.util.concurrent包下的一些的常用类，之前写了AQS、ReentrantLock、ArrayBlockingQueue以及LinkedBlockingQueue的相关博客，今天这篇博客就来写一写并发包下的另一个常用类——CountDownLatch。这里首先要说明一点，CountDownLatch是基于AQS实现的，AQS才是真正实现">
<meta property="og:type" content="article">
<meta property="og:title" content="并发——深入分析CountDownLatch的实现原理">
<meta property="og:url" content="http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/index.html">
<meta property="og:site_name" content="博客主页">
<meta property="og:description" content="一、前言&amp;emsp;&amp;emsp;最近在研究java.util.concurrent包下的一些的常用类，之前写了AQS、ReentrantLock、ArrayBlockingQueue以及LinkedBlockingQueue的相关博客，今天这篇博客就来写一写并发包下的另一个常用类——CountDownLatch。这里首先要说明一点，CountDownLatch是基于AQS实现的，AQS才是真正实现">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-04-13T07:00:13.000Z">
<meta property="article:modified_time" content="2020-04-13T08:57:19.597Z">
<meta property="article:author" content="特务依昂">
<meta property="article:tag" content="并发">
<meta name="twitter:card" content="summary">
    
        <link rel="alternate" type="application/atom+xml" title="博客主页" href="/blog/atom.xml">
    
    <link rel="shortcut icon" href="/blog/img/title.png">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

<meta name="generator" content="Hexo 4.2.0"></head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/blog/img/brand.jpg)">
      <div class="brand">
        <a href="/blog/" class="avatar waves-effect waves-circle waves-light">
          <img src="/blog/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">特务依昂</h5>
          <a href="mailto:1131564805@qq.com" title="1131564805@qq.com" class="mail">1131564805@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/blog/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                博客
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                分类
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/tewuyiang" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://weibo.com/u/5516635708/" target="_blank" >
                <i class="icon icon-lg icon-weibo"></i>
                Weibo
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.cnblogs.com/tuyang1129/" target="_blank" >
                <i class="icon icon-lg icon-link"></i>
                博客园
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">并发——深入分析CountDownLatch的实现原理</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">并发——深入分析CountDownLatch的实现原理</h1>
        <h5 class="subtitle">
            
                <time datetime="2020-04-13T07:00:13.000Z" itemprop="datePublished" class="page-time">
  2020-04-13
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/%E5%B9%B6%E5%8F%91/">并发</a></li></ul>

            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#一、前言"><span class="post-toc-number">1.</span> <span class="post-toc-text">一、前言</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#二、正文"><span class="post-toc-number">2.</span> <span class="post-toc-text">二、正文</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-1-抽象队列同步器AQS"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">2.1 抽象队列同步器AQS</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-2-CountDownLatch的实现原理"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">2.2 CountDownLatch的实现原理</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-3-CountDownLatch的内部类"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">2.3 CountDownLatch的内部类</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-4-CountDownLatch的成员变量和构造方法"><span class="post-toc-number">2.4.</span> <span class="post-toc-text">2.4 CountDownLatch的成员变量和构造方法</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-5-await方法分析"><span class="post-toc-number">2.5.</span> <span class="post-toc-text">2.5 await方法分析</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-6-countDown方法分析"><span class="post-toc-number">2.6.</span> <span class="post-toc-text">2.6 countDown方法分析</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#三、总结"><span class="post-toc-number">3.</span> <span class="post-toc-text">三、总结</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#四、参考"><span class="post-toc-number">4.</span> <span class="post-toc-text">四、参考</span></a></li></ol>
        </nav>
    </aside>


<article id="post-并发——深入分析CountDownLatch的实现原理"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">并发——深入分析CountDownLatch的实现原理</h1>
        <div class="post-meta">
            <time class="post-time" title="2020-04-13 15:00:13" datetime="2020-04-13T07:00:13.000Z"  itemprop="datePublished">2020-04-13</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/%E5%B9%B6%E5%8F%91/">并发</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h1 id="一、前言"><a href="#一、前言" class="headerlink" title="一、前言"></a>一、前言</h1><p>&emsp;&emsp;最近在研究<code>java.util.concurrent</code>包下的一些的常用类，之前写了<code>AQS</code>、<code>ReentrantLock</code>、<code>ArrayBlockingQueue</code>以及<code>LinkedBlockingQueue</code>的相关博客，今天这篇博客就来写一写并发包下的另一个常用类——<code>CountDownLatch</code>。这里首先要说明一点，<code>CountDownLatch</code>是基于<code>AQS</code>实现的，<code>AQS</code>才是真正实现了线程同步的组件，<code>CountDownLatch</code>只是它的使用者，所以<strong>如果想要学习CountDownLatch，请一定先要弄懂AQS的实现原理</strong>。我以下的描述均建立在已经了解<code>AQS</code>的基础之上。我之前写过一篇<code>AQS</code>实现原理的分析博客，感兴趣可以看一看：<a href="https://www.cnblogs.com/tuyang1129/p/12670014.html" target="_blank" rel="noopener">并发——抽象队列同步器AQS的实现原理</a>。</p>
<br>

<h1 id="二、正文"><a href="#二、正文" class="headerlink" title="二、正文"></a>二、正文</h1><h2 id="2-1-抽象队列同步器AQS"><a href="#2-1-抽象队列同步器AQS" class="headerlink" title="2.1 抽象队列同步器AQS"></a>2.1 抽象队列同步器AQS</h2><p>&emsp;&emsp;在说<code>CountDownLatch</code>前，必须要先提一下<code>AQS</code>。<code>AQS</code>全称抽象队列同步器（AbstractQuenedSynchronizer），它是一个可以用来实现线程同步的基础框架。当然，它不是我们理解的<code>Spring</code>这种框架，它是一个类，类名就是<code>AbstractQuenedSynchronizer</code>，如果我们想要实现一个能够完成线程同步的锁或者类似的同步组件，就可以在使用<code>AQS</code>来实现，因为它封装了线程同步的方式，我们在自己的类中使用它，就可以很方便的实现一个我们自己的锁。</p>
<p>&emsp;&emsp;<code>AQS</code>的实现相对复杂，无法通过短短的几句话将其说清楚，我之前专门写过一篇分析<code>AQS</code>实现原理的博客：<a href="https://www.cnblogs.com/tuyang1129/p/12670014.html" target="_blank" rel="noopener">并发——抽象队列同步器AQS的实现原理</a>。</p>
<p>&emsp;&emsp;<strong>在阅读下面的内容前，请一定要先学习AQS的实现原理</strong>，因为<code>CountDownLatch</code>的实现非常简单，完全就是依赖于<code>AQS</code>的，所以我以下的描述均建立在已经理解<code>AQS</code>的基础之上。可以阅读上面推荐博客，也可以自己去查阅相关资料。</p>
<br>

<h2 id="2-2-CountDownLatch的实现原理"><a href="#2-2-CountDownLatch的实现原理" class="headerlink" title="2.2 CountDownLatch的实现原理"></a>2.2 CountDownLatch的实现原理</h2><p>&emsp;&emsp;既然已经开始学习<code>CountDownLatch</code>的实现原理了，那一定已经知道了它的作用，我这里就不详细展示了，简单介绍一下：<code>CountDownLatch</code>的被称为门栓，可以将它看成是门上的锁，它会给门上多把锁，只有每一把锁都解开，才能通过。对于线程来说，<code>CountDownLatch</code>会阻塞线程的运行，只有当<code>CountDownLatc</code>内部记录的值减小为<code>0</code>，线程才能继续向前执行。</p>
<p>&emsp;&emsp;<code>CountDownLatch</code>底层通过<code>AQS</code>实现，<code>AQS</code>的一般使用方式就是以内部类的形式继承它，<code>CountDownLatch</code>就是这么使用它的。在<code>CountDownLatch</code>内部有一个内部类<code>Sync</code>，继承自<code>AQS</code>，并重写了<code>AQS</code>加锁解锁的方法，并通过<code>Sync</code>的对象，调用<code>AQS</code>的方法，阻塞线程的运行。我们知道，创建一个<code>CountDownLatch</code>对象时，需要传入一个整数值<code>count</code>，只有当<code>count</code>被减小为<code>0</code>时线程才能通过<code>await</code>方法，否则将被<code>await</code>阻塞。这里实际上是这样的：<strong>当线程运行到await方法时，需要去获取锁（锁由AQS实现），若count不为0，则线程就会获取锁失败，被阻塞；若count为0，则就能顺利通过</strong>。<code>CountDownLatch</code>是一次性的，因为没有方法可以增加<code>count</code>的值，也就是说，一旦<code>count</code>被减小为<code>0</code>，则之后就一直是<code>0</code>了，也就再也不能阻塞线程了。下面我们就从源码的角度来分析<code>CountDownLatch</code>。</p>
<br>

<h2 id="2-3-CountDownLatch的内部类"><a href="#2-3-CountDownLatch的内部类" class="headerlink" title="2.3 CountDownLatch的内部类"></a>2.3 CountDownLatch的内部类</h2><p>&emsp;&emsp;前面我们说过，<code>CountDownLatch</code>内部定义了一个内部类<code>Sync</code>，继承自<code>AQS</code>，通过这个内部类来实现线程阻塞，下面我们就来看一看这个内部类的实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Sync</span> <span class="keyword">extends</span> <span class="title">AbstractQueuedSynchronizer</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">4982264981922014374L</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** 构造方法，接收count值，只有count减小为0时，线程才不会被await方法阻塞 */</span></span><br><span class="line">    Sync(<span class="keyword">int</span> count) &#123;</span><br><span class="line">        <span class="comment">// CountDownLatch利用AQS的方式就是直接让count作为AQS的同步变量state</span></span><br><span class="line">        <span class="comment">// 所以直接用state记录count值</span></span><br><span class="line">        setState(count);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** 获取当前的count值 */</span></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">getCount</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> getState();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** </span></span><br><span class="line"><span class="comment">     * 这是AQS的模板方法acquireShared、acquireSharedInterruptibly等方法内部将会调用的方法，</span></span><br><span class="line"><span class="comment">     * 由子类实现，这个方法的作用是尝试获取一次共享锁，对于AQS来说，</span></span><br><span class="line"><span class="comment">     * 此方法返回值大于等于0，表示获取共享锁成功，反之则获取共享锁失败，</span></span><br><span class="line"><span class="comment">     * 而在这里，实际上就是判断count是否等于0，线程能否向下运行</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">int</span> <span class="title">tryAcquireShared</span><span class="params">(<span class="keyword">int</span> acquires)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 此处判断state的值是否为0，也就是判断count是否为0，</span></span><br><span class="line">        <span class="comment">// 若count为0，返回1，表示获取锁成功，此时线程将不会阻塞，正常运行</span></span><br><span class="line">        <span class="comment">// 若count不为0，则返回-1，表示获取锁失败，线程将会被阻塞</span></span><br><span class="line">        <span class="comment">// 从这里我们已经可以看出CountDownLatch的实现方式了</span></span><br><span class="line">        <span class="keyword">return</span> (getState() == <span class="number">0</span>) ? <span class="number">1</span> : -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 此方法的作用是用来是否AQS的共享锁，返回true表示释放成功，反之则失败</span></span><br><span class="line"><span class="comment">     * 此方法将会在AQS的模板方法releaseShared中被调用，</span></span><br><span class="line"><span class="comment">     * 在CountDownLatch中，这个方法用来减小count值</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">tryReleaseShared</span><span class="params">(<span class="keyword">int</span> releases)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 使用死循环不断尝试释放锁</span></span><br><span class="line">        <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">            <span class="comment">// 首先获取当前state的值，也就是count值</span></span><br><span class="line">            <span class="keyword">int</span> c = getState();</span><br><span class="line">            <span class="comment">// 若count值已经等于0，则不能继续减小了，于是直接返回false</span></span><br><span class="line">            <span class="comment">// 为什么返回的是false，因为等于0表示之前等待的那些线程已经被唤醒了，</span></span><br><span class="line">            <span class="comment">// 若返回true，AQS会尝试唤醒线程，若返回false，则直接结束，所以</span></span><br><span class="line">            <span class="comment">// 在没有线程等待的情况下，返回false直接结束是正确的</span></span><br><span class="line">            <span class="keyword">if</span> (c == <span class="number">0</span>)</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            <span class="comment">// 若count不等于0，则将其-1</span></span><br><span class="line">            <span class="keyword">int</span> nextc = c-<span class="number">1</span>;</span><br><span class="line">            <span class="comment">// compareAndSetState的作用是将count值从c，修改为新的nextc</span></span><br><span class="line">            <span class="comment">// 此方法基于CAS实现，保证了操作的原子性</span></span><br><span class="line">            <span class="keyword">if</span> (compareAndSetState(c, nextc))</span><br><span class="line">                <span class="comment">// 若nextc == 0，则返回的是true，表示已经没有锁了，线程可以运行了，</span></span><br><span class="line">                <span class="comment">// 若nextc &gt; 0，则表示线程还需要继续阻塞，此处将返回false</span></span><br><span class="line">                <span class="keyword">return</span> nextc == <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;可以看到，内部类Sync的实现非常简单，它只实现了<code>AQS</code>中的两个方法，即<strong>tryAcquireShared</strong>以及<strong>tryReleaseShared</strong>，这两个方法是<code>AQS</code>提供的使用共享锁的接口。这也就表明，<code>CountDownLatch</code>实际上是一种共享锁机制，即锁可以同时被多个线程获取，这个不难理解，因为一旦<code>count</code>被减小为0，则所有线程通过<code>await</code>方法时，都能够顺利通过，不会因为获取不到锁而阻塞。而且从上面的实现中我们可以看到，<code>Sync</code>直接将<code>count</code>值作为<code>AQS</code>的<code>state</code>的值，只有<code>state</code>的值为0，线程才能获取锁，也就是获得执行权限。</p>
<br>

<h2 id="2-4-CountDownLatch的成员变量和构造方法"><a href="#2-4-CountDownLatch的成员变量和构造方法" class="headerlink" title="2.4 CountDownLatch的成员变量和构造方法"></a>2.4 CountDownLatch的成员变量和构造方法</h2><p>&emsp;&emsp;下面来看一看<code>CountDownLatch</code>的属性和构造方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 只有一个成员变量，就是内部类Sync的一个对象，通过此对象调用AQS的方法，实现线程阻塞和唤醒</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Sync sync;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 只有一个构造方法，接收一个count值</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">CountDownLatch</span><span class="params">(<span class="keyword">int</span> count)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// count值不能小于0</span></span><br><span class="line">    <span class="keyword">if</span> (count &lt; <span class="number">0</span>) <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"count &lt; 0"</span>);</span><br><span class="line">    <span class="comment">// 直接创建一个Sync对象，并传入count值，Sync内部将会执行setState(count)</span></span><br><span class="line">    <span class="keyword">this</span>.sync = <span class="keyword">new</span> Sync(count);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<h2 id="2-5-await方法分析"><a href="#2-5-await方法分析" class="headerlink" title="2.5 await方法分析"></a>2.5 await方法分析</h2><p>&emsp;&emsp;<code>CountDownLatch</code>类最最核心的两个方法就是<code>await</code>以及<code>ountDown</code>，我们先来看一看<code>await</code>方法的实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 此方法用来让当前线程阻塞，直到count减小为0才恢复执行</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">await</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    <span class="comment">// 这里直接调用sync的acquireSharedInterruptibly方法，这个方法定义在AQS中</span></span><br><span class="line">    <span class="comment">// 方法的作用是尝试获取共享锁，若获取失败，则线程将会被加入到AQS的同步队列中等待</span></span><br><span class="line">    <span class="comment">// 直到获取成功为止。且这个方法是会响应中断的，线程在阻塞的过程中，若被其他线程中断，</span></span><br><span class="line">    <span class="comment">// 则此方法会通过抛出异常的方式结束等待。</span></span><br><span class="line">    sync.acquireSharedInterruptibly(<span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;<code>await</code>的实现异常简单，只有短短一行代码，调用了<code>AQS</code>中已经封装好的方法。这就是<code>AQS</code>的好处，<code>AQS</code>已经实现了线程的阻塞和唤醒机制，将实现的复杂性隐藏，而其他类只需要简单的使用它即可。为了方便理解，我们还是来看看<code>acquireSharedInterruptibly</code>方法吧：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 此方法是AQS中提供的一个模板方法，用以获取共享锁，并且会响应中断 */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">acquireSharedInterruptibly</span><span class="params">(<span class="keyword">int</span> arg)</span></span></span><br><span class="line"><span class="function">    <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    <span class="comment">// 首先判断当前线程释放被中断，若被中断，则直接抛出异常结束</span></span><br><span class="line">    <span class="keyword">if</span> (Thread.interrupted())</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> InterruptedException();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 调用tryAcquireShared方法尝试获取锁，这个方法被Sycn类重写了，</span></span><br><span class="line">    <span class="comment">// 若count == 0，则这个方法会返回1，表示获取锁成功，则这里会直接返回，线程不会被阻塞</span></span><br><span class="line">    <span class="comment">// 若count &lt; 0，将会执行下面的doAcquireSharedInterruptibly方法，</span></span><br><span class="line">    <span class="comment">// 此处请去查看Sync中tryAcquireShared方法的实现</span></span><br><span class="line">    <span class="keyword">if</span> (tryAcquireShared(arg) &lt; <span class="number">0</span>)</span><br><span class="line">        <span class="comment">// 下面这个方法的作用是，线程获取锁失败，将会加入到AQS的同步队列中阻塞等待，</span></span><br><span class="line">        <span class="comment">// 直到成功获取到锁，而此处成功获取到锁的条件就是count == 0，若当前线程在等待的过程中，</span></span><br><span class="line">        <span class="comment">// 成功地获取了锁，则它会继续唤醒在它后面等待的线程，也尝试获取锁，</span></span><br><span class="line">        <span class="comment">// 这也就是说，只要count == 0了，则所有被阻塞的线程都能恢复运行</span></span><br><span class="line">        doAcquireSharedInterruptibly(arg);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;相信看到这里，对<code>CountDownLatch</code>的实现原理已经有一个比较清晰的理解了。<code>CountDownLatch</code>的实现完全就是依赖于<code>AQS</code>的，所有再次提醒，如果以上内容理解不了，请先去学习<code>AQS</code>。</p>
<br>

<h2 id="2-6-countDown方法分析"><a href="#2-6-countDown方法分析" class="headerlink" title="2.6 countDown方法分析"></a>2.6 countDown方法分析</h2><p>&emsp;&emsp;下面我们来分析<code>CountDownLatch</code>中另一个核心的方法——<code>countDown</code>，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此方法的作用就是将count的值-1，如果count等于0了，就唤醒等待的线程</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">countDown</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 这里直接调用sync的releaseShared方法，这个方法的实现在AQS中，也是AQS提供的模板方法，</span></span><br><span class="line">    <span class="comment">// 这个方法的作用是当前线程释放锁，若释放失败，返回false，若释放成功，则返回false，</span></span><br><span class="line">    <span class="comment">// 若锁被释放成功，则当前线程会唤醒AQS同步队列中第一个被阻塞的线程，让他尝试获取锁</span></span><br><span class="line">    <span class="comment">// 对于CountDownLatch来说，释放锁实际上就是让count - 1，只有当count被减小为0，</span></span><br><span class="line">    <span class="comment">// 锁才是真正被释放，线程才能继续向下运行</span></span><br><span class="line">    sync.releaseShared(<span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;为了方便理解，我们还是来看一看<code>AQS</code>中<code>releaseShared</code>方法的实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">releaseShared</span><span class="params">(<span class="keyword">int</span> arg)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 调用tryReleaseShared尝试释放锁，这个方法已经由Sycn重写，请回顾上面对此方法的分析</span></span><br><span class="line">    <span class="comment">// 若tryReleaseShared返回true，表示count经过这次释放后，等于0了，于是执行doReleaseShared</span></span><br><span class="line">    <span class="keyword">if</span> (tryReleaseShared(arg)) &#123;</span><br><span class="line">        <span class="comment">// 这个方法的作用是唤醒AQS的同步队列中，正在等待的第一个线程</span></span><br><span class="line">        <span class="comment">// 而我们分析acquireSharedInterruptibly方法时已经说过，</span></span><br><span class="line">        <span class="comment">// 若一个线程被唤醒，检测到count == 0，会继续唤醒下一个等待的线程</span></span><br><span class="line">        <span class="comment">// 也就是说，这个方法的作用是，在count == 0时，唤醒所有等待的线程</span></span><br><span class="line">        doReleaseShared();</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<h1 id="三、总结"><a href="#三、总结" class="headerlink" title="三、总结"></a>三、总结</h1><p>&emsp;&emsp;如果直接去看<code>CountDownLatch</code>的源码会发现，它的实现真的非常简单，包括注释在内，总共<code>300</code>行代码，除去注释，连<code>100</code>行代码都不到。因为它所作的工作，除了重写<code>AQS</code>的两个方法外，其余的基本上就是调用<code>AQS</code>提供的模板方法而已。所以，理解<code>CountDownLatch</code>的过程，实际上是理解<code>AQS</code>的过程，只要理解了<code>AQS</code>，看懂<code>CountDownLatch</code>的原理，不需要<code>5</code>分钟。<code>AQS</code>真的是<code>Java</code>并发中非常重要的一个组件，很多类都是基于它实现的，比如还有<code>ReentrantLock</code>，同时<code>AQS</code>也是面试中的常考点，所以一定要好好研究。最后再次推荐我之前编写的有关<code>AQS</code>的源码分析博客：<a href="https://www.cnblogs.com/tuyang1129/p/12670014.html" target="_blank" rel="noopener">并发——抽象队列同步器AQS的实现原理</a>。</p>
<br>

<h1 id="四、参考"><a href="#四、参考" class="headerlink" title="四、参考"></a>四、参考</h1><ul>
<li>JDK1.8源码</li>
</ul>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2020-04-13T08:57:19.597Z" itemprop="dateUpdated">2020-04-13 16:57:19</time>
</span><br>


        
        世界是个球，前方总有路！
        
    </div>
    
    <footer>
        <a href="http://tewuyiang.gitee.io/blog">
            <img src="/blog/img/avatar.jpg" alt="特务依昂">
            特务依昂
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/blog/tags/%E5%B9%B6%E5%8F%91/" rel="tag">并发</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&title=《并发——深入分析CountDownLatch的实现原理》 — 博客主页&pic=http://tewuyiang.gitee.io/blog/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&title=《并发——深入分析CountDownLatch的实现原理》 — 博客主页&source=一个未来程序员的博客~~~" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《并发——深入分析CountDownLatch的实现原理》 — 博客主页&url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&via=http://tewuyiang.gitee.io/blog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ThreadLocal%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">并发——深入分析ThreadLocal的实现原理</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ReentrantLock%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">并发——深入分析ReentrantLock的实现原理</h4>
      </a>
    </div>
  
</nav>



    




















</article>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/blog/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>特务依昂 &copy; 2015 - 2020</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&title=《并发——深入分析CountDownLatch的实现原理》 — 博客主页&pic=http://tewuyiang.gitee.io/blog/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&title=《并发——深入分析CountDownLatch的实现原理》 — 博客主页&source=一个未来程序员的博客~~~" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《并发——深入分析CountDownLatch的实现原理》 — 博客主页&url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&via=http://tewuyiang.gitee.io/blog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/blog/', SHARE: true, REWARD: false };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '人呢，怎么不见了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!欢迎回来!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
